<!--
 * @Descripttion: 违规记录
 * @version:
 * @Author: 赵致喜
 * @Date: 2020-10-14 15:55:45
 * @LastEditors: 穆宏宇
 * @LastEditTime: 2020-11-24 18:43:43
-->
<template>
  <div>
    <div class="control-box">
      <!-- control 操作区 START -->
      <e-control :search-form-options="formOptions"
                  :search-label-width="'100px'"
                 :btns="btns"
                 @on-search="searchControlHandle"
                 @on-refresh="refreshControlHandle"
                 @change-height="changeControlHeight"
                 @on-insert="insertControlHandle"
                 @on-update="updateControlHandle"
                 @on-delete="deleteControlHandle"
                 v-on="$listeners"></e-control>
      <!-- control 操作区 END -->
    </div>
    <div class="table-box">
      <!-- table 数据表格 START -->
      <e-table :data="tableData"
               :columns="columns"
               stripe
               border
               :maxHeight="tableMaxHeight"
               style="width: 100%"
               @row-click="changeTableSelectData"
               :row-class-name="tableRowClassName"
               :current="pageData.pageNum"
               :total="pageData.total"
               @page-size-change="changePageSize"
               @page-current-change="changePageCurrent">
        <template slot-scope="{scope}" slot="violationDetails">
          <el-popover placement="top" trigger="hover">
            <div class="cell-content">{{scope.row.violationDetails}}</div>
            <p class="overflow" slot="reference">{{scope.row.violationDetails}}</p>
          </el-popover>
        </template>
        <template slot-scope="{scope}"
                  slot="operation">
          <el-button v-if="scope.row.attachmentId" type="text" @click="viewImgs(scope.row.attachmentId)" class="clickable">已上传</el-button>
          <span v-else>未上传</span>
        </template>
      </e-table>
      <!-- table 数据表格 END -->
    </div>
    <!-- editDialog 编辑弹窗 START -->
    <el-dialog :title="editDialogTitle"
               :visible.sync="editDialogShow"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               width="50%">
      <el-form ref="editForm"
               :model="formData"
               :rules="formRules"
               label-width="130px">
        <el-card class="box-card"
                 style="overflow: initial;">
          <el-form-item label="供应商名称" prop="supplierName">
            <el-input v-model="formData.supplierName"></el-input>
          </el-form-item>
          <el-form-item label="违规名称" prop="violationName">
            <el-input v-model="formData.violationName"></el-input>
          </el-form-item>
          <el-form-item label="违规详情" prop="violationDetails">
            <el-input type="textarea"
                      show-word-limit
                      maxlength="500"
                      v-model="formData.violationDetails"></el-input>
          </el-form-item>
          <el-form-item label="附件上传">
            <!-- fileType 需要确认参数 -->
            <el-upload :action=fileUrl
                       :data="{ fileType: 9}"
                       :on-preview="handlePreview"
                       :on-remove="handleRemove"
                       :on-success="handleAvatarSuccess"
                       :on-error="handleAvatarError"
                       :on-exceed="handleExceed"
                       :before-upload="beforeAvatarUpload"
                       :on-progress="handleprogress"
                       :headers=fileHeaders
                       multiple
                       :limit="5"
                       :file-list="fileList">
              <el-button size="small"
                         type="primary" v-loading.fullscreen.lock="saveType">点击上传</el-button>
              <div slot="tip"
                   class="el-upload__tip">
                <p style="color: red">*文件限制大小为5M以内,类型为jpg,png,doc,docx,excel,pdf,rar,zip<br />
                  多个附件上传请压缩成rar/zip包后在上传</p>
              </div>
            </el-upload>
          </el-form-item>
        </el-card>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button type="primary"
                   :disabled="saveType"
                   @click="saveDialogDataHandle">提交</el-button>
      </span>
    </el-dialog>
    <!-- editDialog 编辑弹窗 END -->
    <el-dialog :visible.sync="dialogVisiblePicture">
      <div class="demo-image__lazy">
        <el-image v-for="url in pictureUrls" :key="url" :src="url" lazy></el-image>
      </div>
      <ul>
        <li v-for="item in accessoryList" :key="item.id">
          <el-button type="text"  @click="downloadFileFn(item)">{{item.submittedFileName}}</el-button>
        </li>
      </ul>
    </el-dialog>
    <!-- editDialog 放大图片 START -->
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%"
           :src="dialogImageUrl"
           alt="">
    </el-dialog>
    <!-- editDialog 放大图片 END -->
  </div>
</template>

<script>
import eControl from '@/components/e-control'
import { saveOrUpdateViolationRecord, queryViolationRecord, deleteViolationRecord } from '@/api/admin.api'
import { deleteFile, getFileInfo,getFileUrl,queryFileList,downloadFile } from '@/api/common.api'
import { formOptions, btns } from './control'
import columns from './columns'
import { beforeUpload } from '@/util/common'
// 上传文件
import fileUpdata from '@/api/file.config'
export default {
  name: 'violation-record',
  components: {
    eControl
  },
  props: {
  },
  data () {
    return {
      // 表格表头
      columns,
      // 表单配置项
      formOptions,
      // 按钮组
      btns,
      // 弹窗表单数据
      formData: {},
      // 表单校验
      formRules: {
        supplierName: [
          { required: true, trigger: 'blur',message: '请输入供应商姓名'}
        ],
        violationName: [
          { required: true, trigger: 'blur',message: '请输入违规名称'}
        ],
        violationDetails: [
          { required: true, trigger: 'blur',message: '请输入违规详情'}
        ]
      },
      // 附件url
      fileUrl: '',
      // 附件头
      fileHeaders: {},
      // 附件数组
      fileList: [],
      // 编辑框是否展示
      editDialogShow: false,
      editDialogType: 0,
      // 编辑框表单数据
      editFormCurrent: {},
      // 查询表单
      searchFormData: {},
      // 控制区高度
      controlHeight: 0,
      // 表格数据
      tableData: [],
      // 分页数据
      pageData: {
        // 当前分页
        pageNum: 1,
        // 分页条数
        pageSize: 10,
        // 数据总数
        total: 0
      },
      // 表格选中数据
      tableSelectData: {},
      // 获取当前行index
      getIndex: '',
      // 保存按钮状态
      saveType: false,
      // 新增查看文件
      dialogVisible:false,
      dialogImageUrl:'',
      // 列表查看文件
      dialogVisiblePicture: false,
      pictureUrls:[], // 违规上传附件图片
      accessoryList:[] // 违规上传附件
    }
  },
  watch: {},
  computed: {
    // 组合查询条件和分页
    searchData () {
      const { pageNum, pageSize } = this.pageData
      return { ...this.searchFormData, size: pageSize, current: pageNum }
      // return Object.assign(this.searchFormData,{size: pageSize},{current:pageNum})
    },
    //表格最大高度
    tableMaxHeight () {
      return window.innerHeight - this.controlHeight - 160
    },
    // 编辑框标题
    editDialogTitle () {
      return this.editDialogType === 0 ? '新增' : '编辑'
    }
  },
  methods: {
    /**
     * @description 下载附件
     * @author 穆宏宇
     * @date 2020-11-16 09:51:07
     * @param
     * @return
     * */
    downloadFileFn (item) {
      // 下载
      document.location.href = item.url
    },
    // 查看违规附件
    viewImgs (ids){
      queryFileList(9,{sourceIds:ids}).then(res=>{
        // console.log(res)
        this.pictureUrls = []
        this.accessoryList = []
        res.forEach(item=>{
         if (['image/png','image/jpeg'].includes(item.contextType) ){
           this.pictureUrls.push(item.url)
         } else {
           this.accessoryList.push(item)
         }
        })
        this.dialogVisiblePicture = true
      })
    },
    // 预览附件
    handlePreview (file) {
      getFileInfo(file.fileType, file.id).then(res => {
        if (['image/png','image/jpeg'].includes(res.contextType)) {
            this.dialogImageUrl = res.url
            this.dialogVisible = true
        } else {
          this.downloadFileFn(res)
        }
      })
    },
    // 删除附件
    handleRemove (file, fileList) {
      if (file && file.status === 'success') {
        this.fileList = this.fileList.filter(item => item.id !== file.id)
      }
    },
    // 上传文件提示
    handleExceed (files, fileList) {
      this.$message.warning('最多可上传 5 个附件，您已超限')
      // this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    // 上传时钩子
    handleprogress () {},
    // 上传成功时
    handleAvatarSuccess (res, file) {
      const curFile = {
        name: res.data.submittedFileName,
        url: res.data.url,
        id: res.data.id,
        fileType: res.data.fileType
      }
      this.fileList.push(curFile)
      const ids = []
      this.fileList.map(item => {
        ids.push(item.id)
      })
      this.formData.attachmentId = ids.toString()
      this.saveType = false
    },
    // 上传错误文件时提示
    handleAvatarError (res, file) {
      this.$message.error('文件上传失败，请重试')
    },
    // 上传文件校验
    beforeAvatarUpload (file) {
      this.saveType = true
      //const isJPG = file.type === 'image/jpeg';
      const typeList = ['jpg', 'png', 'doc', 'docx', 'excel', 'pdf', 'rar', 'zip']
      const isJPG = beforeUpload(file, typeList)
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isJPG) {
        this.$message.error('上传文件格式不符合!')
        this.saveType = false
      }
      if (!isLt5M) {
        this.$message.error('上传附件大小不能超过 5MB!')
        this.saveType = false
      }
      return isJPG && isLt5M
    },
    // 页面初始化
    init () {
      this.getTableData()
    },
    // 检索违规记录列表
    searchControlHandle (data) {
      this.searchFormData = data
      this.refreshPageCurrent()
    },
    // 重置搜索条件
    refreshControlHandle (data) {
      this.searchFormData = data
    },
    // 搜索区动态高度
    changeControlHeight (height) {
      this.controlHeight = height
    },
    // 重置数据项
    refreshData () {
      this.formData = {}
      this.tableSelectData = {}
      this.getIndex = ''
      this.fileList = []
    },
    // 新增弹窗
    insertControlHandle () {
      this.refreshData()
      this.$nextTick(() => {
        this.openDialog(0)
      })
    },
    // 编辑弹窗
    updateControlHandle () {
      if (this.tableSelectData.id === undefined) {
        this.$alert('至少选择一条数据！', '提示', {
          confirmButtonText: '确定'
        })
        return false
      }
      // 反查选中行数据
      queryViolationRecord({ id: this.tableSelectData.id }).then(res => {
        this.formData = res.records[0]
        // 根据选中行id反查文件
        if (this.formData.attachmentId) {
          const ids = this.formData.attachmentId.split(',')
          ids.map(item => {
            getFileInfo('9', item).then(res => {
              const fileInfo = {
                name: res.submittedFileName,
                url: res.url,
                id: res.id,
                fileType: res.fileType
              }
              this.fileList.push(fileInfo)
            })
          })
        }
      })
      this.openDialog(1)
    },
    // 点击删除按钮，并获取选中id
    deleteControlHandle () {
      const id = this.tableSelectData.id
      this.deleteTableHandle(id)
    },
    // 绑定对应对应class
    tableRowClassName ({ row, rowIndex }) {
      row.index = rowIndex
      if ((this.getIndex) === rowIndex) {
        return 'active-td'
      }
    },
    // 获取选中行数据
    changeTableSelectData (row) {
      this.getIndex = row.index
      this.tableSelectData = row
    },
    // 获取列表条数，查询数据
    changePageSize (size) {
      this.pageData.pageSize = size
      this.getTableData()
    },
    // 获取当前分页，查询数据
    changePageCurrent (current) {
      this.pageData.pageNum = current
      this.getTableData()
    },
    // 重置分页，查询数据
    refreshPageCurrent () {
      this.pageData.pageNum = 1
      this.getTableData()
    },
    // 请求列表数据
    getTableData () {
      queryViolationRecord(this.searchData).then(res => {
        this.tableData = res.records
        this.pageData.total = res.total
      })
    },
    // 删除数据
    deleteTableHandle (id) {
      if (id === undefined) {
        this.$alert('至少选择一条数据！', '提示', {
          confirmButtonText: '确定'
        })
        return false
      }
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteViolationRecord(id).then(res => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.getTableData()
        })
      }).catch(() => {
        this.refreshData()
        this.refreshPageCurrent()
      })
    },
    // 打开弹窗
    openDialog (type = 0) {
      this.editDialogType = type
      this.editDialogShow = true
    },
    // 关闭弹窗
    closeDialog () {
      this.editDialogType = 0
      this.editDialogShow = false
    },
    // 保存违规记录
    saveDialogDataHandle () {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          saveOrUpdateViolationRecord(this.formData).then(res => {
            this.fileList = []
            this.$refs.editForm.resetFields()
            this.closeDialog()
            this.$message({
              message: '保存成功',
              type: 'success'
            })
            this.getTableData()
            this.refreshData()
            this.refreshPageCurrent()
          })
        }
      })
    }
  },
  created () { },
  mounted () {
    // 文件请求头
    this.fileHeaders = { ...fileUpdata.headers() }
    this.fileUrl = fileUpdata.url
    this.init()
  }
}
</script>
<style lang="scss">
.control-box {
  margin-bottom: 10px;
}
.text-right {
  text-align: right;
}
.pd5 {
  padding: 5px;
}
.active-td td {
  background-color: #cae1ff !important;
}
.hide .el-upload--picture-card {
  display: none;
}
.cell-content {
  width: 200px;
  min-height: 20px;
  max-height: 200px;
  overflow-y: auto;
}
.overflow {
  width: 118px;
  overflow:hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow:ellipsis;
  overflow: hidden;
}
.clickable{
  color: $--color-primary;
}
</style>
